package com.cssw.fyzb.busi.api.acct;

import com.cssw.fyzb.core.exception.BizException;
import com.cssw.fyzb.busi.service.acct.UserCashOutService;
import com.cssw.fyzb.busi.service.user.UserService;
import com.cssw.fyzb.core.model.dodb.User;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.simplelock.SimpleLock;
import com.ydn.simplelock.SimpleLockFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @Author zhouxu
 * @create 2020-12-23 22:05
 */
@Function(description = "音值提现", parameters = {
        @Parameter(name = "userId", type = Type.String, description = "用户标识", required = true),
        @Parameter(name = "num", type = Type.Decimal, description = "数量", required = true),
        @Parameter(name = "tradePwd", type = Type.String, description = "交易密码", required = true),
        @Parameter(name = "payMethod", type = Type.String, description = "提现方式（1微信 2支付宝 3银行卡）", required = true),
        @Parameter(name = "bankId", type = Type.String, description = "银行卡标识", required = false),
})
@Component
public class CashOutYCoin implements Action {

    private static Logger logger = LoggerFactory.getLogger(CashOutYCoin.class);

    @Autowired
    private UserCashOutService userCashOutService;

    @Autowired
    private UserService userService;

    @Autowired
    SimpleLockFactory simpleLockFactory;

    @Override
    public Response execute(Request request) throws Exception {

        Long userId = request.getLong("userId");
        String tradePwd = request.getString("tradePwd");
        String num = request.getString("num");
        String payMethod = request.getString("payMethod");
        Long bankId = request.getLong("bankId");

        // 校验支付密码
        User user = userService.getByTradePwd(userId, tradePwd);
        if (user == null) {
            return Response.fail("交易密码不正确");
        }
        // 获取锁
        SimpleLock lock = simpleLockFactory.getLock("USER_"+userId);

        try {
            lock.acquire();
            userCashOutService.cashOutYCoin(userId, new BigDecimal(num), payMethod, bankId);

            return Response.success();
        } catch (BizException e) {
            logger.error(e.getErrMsg(), e.getErrCode());
            return Response.fail(e.getErrMsg(), e.getErrCode());
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail(e);
        } finally {
            lock.release();
        }

    }
}
